<?php
namespace app\common\service;

use support\Db;
use support\Log;

/**
 * 会员自动到期处理服务
 */
class MembershipDaemonService
{
    /**
     * 处理即将到期的会员
     */
    public static function processExpiringMemberships()
    {
        try {
            Log::info('Starting membership expiration processing');
            
            // 获取即将到期的会员（7天内到期）
            $expiringSoon = Db::table('gf_user_memberships')
                ->where('status', 'active')
                ->where('membership_end_date', '<=', date('Y-m-d', strtotime('+7 days')))
                ->where('membership_end_date', '>', date('Y-m-d'))
                ->where('reminded', 0)
                ->get();
                
            foreach ($expiringSoon as $membership) {
                self::sendExpirationReminder($membership);
            }
            
            // 获取已经到期的会员
            $expiredMemberships = Db::table('gf_user_memberships')
                ->where('status', 'active')
                ->where('membership_end_date', '<=', date('Y-m-d'))
                ->get();
                
            foreach ($expiredMemberships as $membership) {
                self::processExpiredMembership($membership);
            }
            
            Log::info('Membership expiration processing completed', [
                'expiring_soon_count' => count($expiringSoon),
                'expired_count' => count($expiredMemberships)
            ]);
            
        } catch (\Exception $e) {
            Log::error('Membership expiration processing failed: ' . $e->getMessage());
        }
    }
    
    /**
     * 发送到期提醒
     */
    private static function sendExpirationReminder($membership)
    {
        try {
            $user = Db::table('gf_users')
                ->where('id', $membership->user_id)
                ->first();
                
            if (!$user) {
                return;
            }
            
            $daysUntilExpiry = (strtotime($membership->membership_end_date) - time()) / (60 * 60 * 24);
            
            // 这里可以集成邮件发送、短信通知等功能
            // 暂时记录到用户日志中
            MembershipService::logUserAction(
                $membership->user_id,
                'membership_expiring_soon',
                'membership',
                $membership->id,
                null,
                [
                    'days_until_expiry' => ceil($daysUntilExpiry),
                    'membership_end_date' => $membership->membership_end_date
                ]
            );
            
            // 标记为已提醒
            Db::table('gf_user_memberships')
                ->where('id', $membership->id)
                ->update(['reminded' => 1]);
                
            Log::info("Sent expiration reminder to user {$user->username}", [
                'membership_id' => $membership->id,
                'days_until_expiry' => ceil($daysUntilExpiry)
            ]);
            
        } catch (\Exception $e) {
            Log::error("Failed to send expiration reminder: " . $e->getMessage());
        }
    }
    
    /**
     * 处理已到期的会员
     */
    private static function processExpiredMembership($membership)
    {
        try {
            Db::beginTransaction();
            
            // 更新会员状态为已过期
            Db::table('gf_user_memberships')
                ->where('id', $membership->id)
                ->update([
                    'status' => 'expired',
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            
            // 检查用户是否有其他有效的会员
            $activeMemberships = Db::table('gf_user_memberships')
                ->where('user_id', $membership->user_id)
                ->where('status', 'active')
                ->count();
                
            if ($activeMemberships === 0) {
                // 用户没有有效会员，降级到基础版
                $basicPlan = Db::table('gf_membership_plans')
                    ->where('plan_type', 'basic')
                    ->first();
                    
                if ($basicPlan) {
                    // 创建基础版会员记录（免费版）
                    Db::table('gf_user_memberships')->insert([
                        'user_id' => $membership->user_id,
                        'plan_id' => $basicPlan->id,
                        'plan_type' => 'basic',
                        'membership_start_date' => date('Y-m-d'),
                        'membership_end_date' => date('Y-m-d', strtotime('+100 years')), // 永久有效
                        'status' => 'active',
                        'auto_renew' => 0,
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                    
                    // 记录用户操作日志
                    MembershipService::logUserAction(
                        $membership->user_id,
                        'membership_downgraded_to_basic',
                        'membership',
                        $membership->id,
                        null,
                        [
                            'previous_plan' => $membership->plan_type,
                            'new_plan' => 'basic'
                        ]
                    );
                }
            }
            
            // 记录用户操作日志
            MembershipService::logUserAction(
                $membership->user_id,
                'membership_expired',
                'membership',
                $membership->id,
                null,
                [
                    'plan_type' => $membership->plan_type,
                    'expiry_date' => $membership->membership_end_date
                ]
            );
            
            Db::commit();
            
            Log::info("Processed expired membership for user {$membership->user_id}", [
                'membership_id' => $membership->id,
                'plan_type' => $membership->plan_type
            ]);
            
        } catch (\Exception $e) {
            Db::rollBack();
            Log::error("Failed to process expired membership: " . $e->getMessage());
        }
    }
    
    /**
     * 处理自动续费
     */
    public static function processAutoRenewals()
    {
        try {
            Log::info('Starting auto-renewal processing');
            
            // 获取需要自动续费的会员（到期前3天）
            $autoRenewals = Db::table('gf_user_memberships')
                ->where('status', 'active')
                ->where('auto_renew', 1)
                ->where('membership_end_date', '<=', date('Y-m-d', strtotime('+3 days')))
                ->where('membership_end_date', '>', date('Y-m-d'))
                ->get();
                
            foreach ($autoRenewals as $membership) {
                self::processAutoRenewal($membership);
            }
            
            Log::info('Auto-renewal processing completed', [
                'processed_count' => count($autoRenewals)
            ]);
            
        } catch (\Exception $e) {
            Log::error('Auto-renewal processing failed: ' . $e->getMessage());
        }
    }
    
    /**
     * 处理单个自动续费
     */
    private static function processAutoRenewal($membership)
    {
        try {
            $user = Db::table('gf_users')
                ->where('id', $membership->user_id)
                ->first();
                
            if (!$user) {
                return;
            }
            
            // 获取会员套餐信息
            $plan = Db::table('gf_membership_plans')
                ->where('id', $membership->plan_id)
                ->first();
                
            if (!$plan) {
                return;
            }
            
            // 检查用户余额
            $balance = Db::table('gf_user_balances')
                ->where('user_id', $membership->user_id)
                ->first();
                
            $renewalAmount = $plan->price; // 原价续费
            
            // 如果用户有余额，使用余额支付（享受折扣）
            if ($balance && $balance->balance >= $renewalAmount * 0.9) {
                // 使用余额自动续费，享受9折优惠
                $finalAmount = $renewalAmount * 0.9;
                
                // 调用余额支付服务
                $balanceController = new \app\api\controller\BalanceController();
                $result = $balanceController->processBalancePayment(
                    $membership->user_id,
                    $finalAmount,
                    'membership_renew',
                    $membership->id,
                    "会员自动续费 - {$plan->name}"
                );
                
                if ($result['code'] === 200) {
                    // 续费成功，延长会员期限
                    $newEndDate = date('Y-m-d', strtotime($membership->membership_end_date . ' +1 month'));
                    
                    Db::table('gf_user_memberships')
                        ->where('id', $membership->id)
                        ->update([
                            'membership_end_date' => $newEndDate,
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);
                    
                    // 记录自动续费记录
                    Db::table('gf_auto_charge_records')->insert([
                        'user_id' => $membership->user_id,
                        'membership_id' => $membership->id,
                        'amount' => $renewalAmount,
                        'discount_rate' => 90,
                        'final_amount' => $finalAmount,
                        'charge_type' => 'membership_renew',
                        'status' => 'success',
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                    
                    // 记录用户操作日志
                    MembershipService::logUserAction(
                        $membership->user_id,
                        'membership_auto_renewed',
                        'membership',
                        $membership->id,
                        null,
                        [
                            'plan_name' => $plan->name,
                            'amount' => $finalAmount,
                            'new_end_date' => $newEndDate
                        ]
                    );
                    
                    Log::info("Auto-renewal successful for user {$user->username}", [
                        'membership_id' => $membership->id,
                        'amount' => $finalAmount
                    ]);
                } else {
                    Log::warning("Auto-renewal failed for user {$user->username}: " . $result['msg']);
                }
            } else {
                // 余额不足，发送续费失败通知
                MembershipService::logUserAction(
                    $membership->user_id,
                    'membership_auto_renewal_failed',
                    'membership',
                    $membership->id,
                    null,
                    [
                        'reason' => '余额不足',
                        'required_amount' => $renewalAmount * 0.9,
                        'current_balance' => $balance ? $balance->balance : 0
                    ]
                );
                
                Log::warning("Auto-renewal failed for user {$user->username}: insufficient balance");
            }
            
        } catch (\Exception $e) {
            Log::error("Auto-renewal processing failed for membership {$membership->id}: " . $e->getMessage());
        }
    }
}